<!--
 * @Author: 260156 260156@gree.com.cn
 * @Date: 2022-08-10 16:23:25
 * @LastEditors: 260156 260156@gree.com.cn
 * @LastEditTime: 2022-08-18 15:58:07
 * @FilePath: \gree-zst-web\src\views\manage\organization\components\EditAddForm.vue
 * @Description: 新增和编辑弹框
 * 
 * Copyright (c) 2022 by 260156 260156@gree.com.cn, All Rights Reserved. 
-->
<template>
  <el-dialog
    :title="title"
    width="500px"
    @open="handleOpen"
    @close="handleClose"
  >
    <el-form
      :model="form"
      :rules="rules"
      label-width="100px"
      class="edit-add-form"
      ref="formRef"
    >
      <el-form-item label="组织名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleConfirm(formRef)">确认</el-button>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { EditForm } from "../types";
import { cloneDeep } from "lodash";
import { requiredValidate, lengthValidate } from "utils/validate";
import type { FormInstance, FormRules } from "element-plus";

interface Props {
  flag?: "edit" | "add";
  formData?: EditForm;
}
const props = withDefaults(defineProps<Props>(), {
  flag: "edit",
});

interface DefineEmits {
  (e: "handleConfirm", formData: EditForm): void; // 自定义事件
  (e: "handleClose"): void; // 自定义事件
  (e: "update:modelValue", visible: boolean): void;
}
const emits = defineEmits<DefineEmits>();

const formRef = ref<FormInstance>();
const rules = ref<FormRules>({
  name: [requiredValidate(), lengthValidate(20)],
});

const initForm: EditForm = {
  name: "",
};

const form = ref<EditForm>(cloneDeep(initForm));

const title = computed(() => (props.flag === "edit" ? "编辑" : "新增"));

// 弹框打开和关闭
const handleClose = () => {
  form.value = cloneDeep(initForm);
  // 点击X关闭弹框时，需要更新visible
  emits("update:modelValue", false);
};
const handleOpen = () => {
  props.flag === "edit" && (form.value = cloneDeep(props.formData as EditForm)); // 更新表单数据
  formRef.value && formRef.value.clearValidate();
};

// 点击取消和确认按钮
const handleCancel = () => {
  emits("handleClose");
  // 点击取消按钮时，需要更新visible
  emits("update:modelValue", false);
};
const handleConfirm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      emits("handleConfirm", form.value);
      // 点击确认按钮时，需要在父组件api调用成功后更新visible，此处不做更新
    }
  });
};
</script>
